import React, {useEffect, useRef, useState} from 'react';
import {
    ScrollView,
    View,
    Image,
    Text,
    TouchableOpacity,
    StyleSheet,
    Linking
} from 'react-native';
import {connect} from 'react-redux';
import Swiper from 'react-native-swiper';
import {LoadingView, Ticon, Toast} from "react-native-gzdsx-elements";
import RenderHtml from 'react-native-render-html';
import SkuPannel from "./components/SkuPannel";
import {ShareView} from '../../components';
import {defaultNavigationConfigure} from "../../base/navconfig";
import {Size, StatusBarStyles} from '../../styles';
import GoodsActionBar from "./components/GoodsActionBar";
import FastImage from "react-native-fast-image";
import CartActions from "./CartActions";
import Icon from "react-native-vector-icons/AntDesign";
import {useNavigation, useRoute} from "@react-navigation/native";
import ApiService from "../../utils/ApiService";
import StatusBarCtl from "../../utils/StatusBarCtl";
import CartService from "./utils/CartService";

const getContent = (content) => {
    return `<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />` +
        `<style type="text/css">*{max-width: 100%;}img{max-width: 100%; display: block;}</style></head>` +
        `<body>${content || ''}</body></html>`;
};

const ProductSwiper = ({images = []}) => {
    return (
        <Swiper
            style={{height: Size.screenWidth * 0.8}}
            activeDotColor={"#fff"}
            autoplay
        >
            {
                images.map((image, index) => (
                    <TouchableOpacity style={{flex: 1}} activeOpacity={1} key={index.toString()}>
                        <FastImage
                            source={{uri: image.image}}
                            style={{
                                width: Size.screenWidth,
                                height: Size.screenWidth * 0.8
                            }}
                            resizeMode={FastImage.resizeMode.cover}
                        />
                    </TouchableOpacity>
                ))
            }
        </Swiper>
    );
}

const ProductInfo = ({product = {}}) => {
    return (
        <View style={{
            backgroundColor: '#fff',
            padding: 15
        }}>
            <View style={{marginBottom: 10}}>
                <Text style={{
                    flex: 1,
                    fontSize: 16,
                    color: '#000',
                    lineHeight: 20,
                    fontWeight: '600',
                }}>{product.title}</Text>
            </View>
            <View style={{flexDirection: 'row'}}>
                <Text style={{color: '#f40', fontSize: 14, paddingTop: 4}}>￥</Text>
                <Text style={{
                    fontSize: 18,
                    fontWeight: 'bold',
                    color: '#f40',
                    marginRight: 20
                }}>{product.price}</Text>
                <Text style={{
                    fontSize: 14,
                    color: '#777',
                    paddingTop: 4
                }}>原价:{product.original_price}</Text>
            </View>
            <View style={{
                flexDirection: 'row',
                marginTop: 20
            }}>
                <Text style={{
                    flex: 1,
                    fontSize: 12,
                    color: '#777'
                }}>配送费:{product.shipping_fee > 0 ? product.shipping_fee : '免费'}</Text>
                <View style={{flex: 1}}/>
                <Text style={{
                    fontSize: 12,
                    color: '#777',
                    textAlign: 'right'
                }}>已售{product.sold}件</Text>
            </View>
        </View>
    );
}

const ProductShop = ({shop = {}}) => {
    const navigation = useNavigation();
    return (
        <View style={styles.shopContainer}>
            <View style={styles.shopInfo}>
                <Image source={{uri: shop.logo}} style={styles.shopLogo}/>
                <View style={{flex: 1, paddingTop: 5}}>
                    <Text style={styles.shopName}>{shop.shop_name}</Text>
                    <Text style={styles.shopLocation}>{shop.province} {shop.city}{shop.district}</Text>
                </View>
            </View>
            <View style={styles.shopData}>
                <View style={[styles.shopDataItem, {borderLeftWidth: 0}]}>
                    <Text style={styles.shopDataText}>{shop.visitors}</Text>
                    <Text style={styles.shopDataText}>访客数</Text>
                </View>
                <View style={styles.shopDataItem}>
                    <Text style={styles.shopDataText}>{0}</Text>
                    <Text style={styles.shopDataText}>商品数</Text>
                </View>
                <View style={styles.shopDataItem}>
                    <Text style={styles.shopDataText}>{shop.cumulative_sales}</Text>
                    <Text style={styles.shopDataText}>累计销量</Text>
                </View>
            </View>
            <View style={styles.viewShopWarp}>
                <Text
                    style={styles.viewShopText}
                    suppressHighlighting={true}
                    onPress={() => {
                        navigation.navigate('ShopDetail', {shop_id: shop.shop_id})
                    }}>进店看看</Text>
            </View>
        </View>
    );
}

const ProductContent = ({content = {}}) => {
    return (
        <View>
            <View style={{
                paddingVertical: 10,
                marginTop: 10
            }}>
                <Text style={{
                    textAlign: 'center',
                    fontSize: 16,
                    color: '#666'
                }}>宝贝详情</Text>
            </View>

            <RenderHtml
                source={{html: content.content}}
                contentWidth={Size.screenWidth}
                ignoredStyles={['fontFamily']}
                renderersProps={{
                    img: {
                        enableExperimentalPercentWidth: true
                    }
                }}
                tagsStyles={{
                    p: {
                        marginTop: 0
                    }
                }}
            />
        </View>
    );
}

const ProductRemoved = () => {
    return (
        <View style={{flex: 1}}>
            <View style={{flex: 1}}/>
            <View style={{alignItems: 'center', alignSelf: 'center'}}>
                <Ticon name={"off-sale"} size={80} color={"#F24F53"}/>
                <View style={{padding: 20, alignItems: 'center', alignContent: 'center'}}>
                    <Text style={{
                        fontSize: 18,
                        color: '#000',
                        textAlign: 'center'
                    }}>商品已下架</Text>
                </View>
            </View>
            <View style={{flex: 1}}/>
            <View style={{flex: 1}}/>
        </View>
    )
}

const ProductDetail = ({oauth}) => {
    const route = useRoute();
    const navigation = useNavigation();

    const [loading, setLoading] = useState(true);
    const [product, setProduct] = useState({});
    const [content, setContent] = useState({});
    const [images, setImages] = useState([]);
    const [props, setProps] = useState([]);
    const [shop, setShop] = useState({});
    const [showSku, setShowSku] = useState(false);
    const [removed, setRemoved] = useState(false);

    const shareRef = useRef(null);
    const actionType = useRef(1);

    useEffect(() => {
        navigation.setOptions({
            ...defaultNavigationConfigure(navigation),
            title: '宝贝详情',
        });
        fetchData();
    }, []);

    useEffect(() => {
        return navigation.addListener('focus', () => {
            StatusBarCtl.setToDarkStyle();
        });
    }, [navigation]);


    const setNavigationRight = () => {
        navigation.setOptions({
            headerRight: () => (
                <View style={{flexDirection: 'row'}}>
                    <Icon
                        size={25}
                        name={'shoppingcart'}
                        color={'#333'}
                        suppressHighlighting={true}
                        onPress={() => {
                            navigation.navigate('cart');
                        }}
                    />
                    <View style={{width: 10}}/>
                    <Icon
                        name={'sharealt'}
                        size={25}
                        color={"#333"}
                        suppressHighlighting={true}
                        onPress={() => {
                            this.share.show();
                        }}
                    />
                </View>
            ),
            hideWhenScrolling: true
        });
    }

    const fetchData = () => {
        let id = route.params?.id;
        ApiService.get('/products/' + id).then(response => {
            setProduct(response.result);
            const {images, props, shop, content} = response.result;
            if (images) setImages(images);
            if (props) setProps(props);
            if (shop) setShop(shop);
            if (content) setContent(content);
            setNavigationRight();
            setRemoved(false);
        }).catch(reason => {
            //console.log(reason);
            setRemoved(true);
        }).finally(() => {
            setLoading(false);
        });
    }

    if (loading) {
        return <LoadingView/>;
    }

    if (removed) {
        return <ProductRemoved/>;
    }

    return (
        <View style={{flex: 1}}>
            <ScrollView style={{flex: 1, backgroundColor: '#f5f5f5'}}>
                <ProductSwiper images={images}/>
                <ProductInfo product={product}/>
                <ProductShop shop={shop}/>
                <ProductContent content={content}/>
            </ScrollView>
            <GoodsActionBar
                product={product}
                onPressAddCart={() => {
                    actionType.current = 1;
                    if (!oauth.isAuthenticated) {

                    }

                    setShowSku(true);
                }}
                onPressBuyNow={() => {
                    actionType.current = 2;
                    if (!oauth.isAuthenticated) {

                    }
                    setShowSku(true);
                }}
                onConnectKefu={() => {
                    Linking.openURL('tel:18685849696');
                }}
            />
            <SkuPannel
                show={showSku}
                product={product}
                onClose={() => {
                    setShowSku(false);
                }}
                onSubmit={(sku, quantity) => {
                    setShowSku(false);
                    const sku_id = sku.sku_id || 0;
                    const product_id = product.id;
                    if (actionType.current === 1) {
                        CartService.addToCart(product_id, quantity, sku_id).then(() => {
                            Toast.success('已成功加入购物车');
                        }).catch(reason => {
                            Toast.fail(reason.message);
                        });
                    } else {
                        navigation.navigate('Checkout', {product_id, quantity, sku_id});
                    }
                }}
            />
            <ShareView ref={shareRef}/>
        </View>
    )
}

const styles = StyleSheet.create({
    shopContainer: {
        backgroundColor: '#fff',
        paddingVertical: 20,
        paddingHorizontal: 10,
        marginTop: 10
    },
    shopInfo: {
        flexDirection: 'row',
    },
    shopLogo: {
        width: 50,
        height: 50,
        borderRadius: 25,
        marginRight: 10
    },
    shopName: {
        fontSize: 16,
        fontWeight: '600',
        color: '#333'
    },
    shopLocation: {
        fontSize: 14,
        color: '#777',
        marginTop: 5
    },
    shopData: {
        flexDirection: 'row',
        marginTop: 10
    },
    shopDataText: {
        fontSize: 13,
        textAlign: 'center',
        color: '#777',
        marginTop: 5
    },
    shopDataItem: {
        borderLeftWidth: 0.5,
        borderLeftColor: '#e0e0e0',
        flex: 1,
        paddingBottom: 5
    },
    viewShopText: {
        textAlign: 'center',
        paddingLeft: 20,
        paddingRight: 20,
        paddingTop: 8,
        paddingBottom: 8,
        color: '#ff0000',
        fontSize: 14,
        borderWidth: 1,
        borderColor: '#ff0000',
        borderRadius: 10
    },
    viewShopWarp: {
        marginTop: 15,
        alignContent: 'center',
        alignItems: 'center'
    }
});

const mapStateToProps = state => {
    return state;
};

export default connect(mapStateToProps)(ProductDetail);
